package org.wlw.servlet;

import org.wlw.anno.Resource;
import org.wlw.models.Movie;
import org.wlw.service.IMovieService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/admin/movie")
public class MovieServlet extends BaseServlet{
    private IMovieService movieService;

    @Resource
    public void setMovieService(IMovieService movieService) {
        this.movieService = movieService;
    }

    public String index(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setAttribute("movies",movieService.list());
        return "/movie/list";
    }

    public String add(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        return "/movie/add";
    }

    public String addAction(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //完成添加
        String name = req.getParameter("name");
        String type = req.getParameter("type");
        String director = req.getParameter("director");
        String actor = req.getParameter("actor");
        double score = Double.parseDouble(req.getParameter("score"));
        Movie movie = new Movie();
        movie.setActor(actor);
        movie.setDirector(director);
        movie.setName(name);
        movie.setScore(score);
        movie.setType(type);
        movieService.add(movie);
        return getRedirectUrl("/admin/movie");
    }

    public String delete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        int id = Integer.parseInt(req.getParameter("id"));
        movieService.delete(id);
        return getRedirectUrl("/admin/movie");
    }

    public String update(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        int id = Integer.parseInt(req.getParameter("id"));
        Movie movie = movieService.load(id);
        req.setAttribute("movie",movie);
        return "/movie/update";
    }

    public String updateAction(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        int id = Integer.parseInt(req.getParameter("id"));
        Movie tm = movieService.load(id);
        tm.setType(req.getParameter("type"));
        tm.setName(req.getParameter("name"));
        tm.setScore(Double.parseDouble(req.getParameter("score")));
        tm.setDirector(req.getParameter("director"));
        tm.setActor(req.getParameter("actor"));
        movieService.update(tm);
        return getRedirectUrl("/admin/movie");
    }
}
